<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>MESSAGE</title>
</head>
<body>
<div id="message-head">
  HAPPY MESSAGE SYSTEM
</div>
<div id="user_status"></div>
<div id="message"></div>
<div id ="message-body">
    <input id="msg" type="text" placeholder="消息内容"/>
    <input id="toUser" type="text" placeholder="发送给谁">
  <button onclick="send()"> Send </button>
  <button onclick="closeWebSocket()"> Close </button>
</div>



<script type="text/javascript">
  var userId =Math.floor(Math.random()*10)+ 1;
  //判断当前浏览器是否支持WebSocket
  if('WebSocket' in window){
    websocket = new WebSocket("ws://127.0.0.1:8081/imserver/"+userId);
    console.log("link success")
  }else{
    alert('Not support websocket')
  }

  //连接发生错误的回调方法
  websocket.onerror = function(){
    setMessageInnerHTML("error");
  };

  //连接成功建立的回调方法
  websocket.onopen = function(event){
    // setMessageInnerHTML("登录信息展示:");
    setOnLineInnerHTML("登录信息展示:");
  }
  console.log("-----")
  //接收到消息的回调方法
  websocket.onmessage = function(event){
    let data = event.data
    console.log("回调消息:"+data)
    //别人给我发送消息
    if(data.toString().indexOf("toUserId")!==-1 && data.toString().indexOf("fromUserId")!==-1){
      setMessageInnerHTML(event.data);
    }else if ((data.toString().indexOf("fromUserId")===-1  && data.toString().indexOf("toUserId")!==-1)){
      setMessageInnerHTML(event.data);
    }else {
      setOnLineInnerHTML(event.data)
    }
  }

  //连接关闭的回调方法
  websocket.onclose = function(){
    let date = formatDate(new Date(),"yyyy-MM-dd hh:mm:ss");
    var off = "Yourself_ID : "+userId+" ==>  状态 : <font-family style='color: red'>离线</font-family>"+"  ==> 时间 : "+date
    setOnLineInnerHTML(off);
  }

  //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
  window.onbeforeunload = function(){
    websocket.close();
  }

  //将消息显示在网页上
  function setMessageInnerHTML(innerHTML){

    document.getElementById('message').innerHTML += innerHTML + '<br/>';
  }

  //将登录状态显示在网页上
  function setOnLineInnerHTML(innerHTML){
    document.getElementById('user_status').innerHTML += innerHTML + '<br/>';
  }
  //关闭连接
  function closeWebSocket(){
    websocket.close();
  }

  //发送消息
  function send(){
    var message = document.getElementById('msg').value;
    var toUser = document.getElementById('toUser').value;
    var data ;
    //群聊
    if(toUser==null || toUser===""){
      data = {
        msg: message
      }
    }else {
      //指定用户
      let s = message.toString();
      data = {
        toUserId: toUser,
        msg: message
      }
    }
    var todata = JSON.stringify(data);
    websocket.send(todata);
  }

  function formatDate(date, fmt) {
    if (typeof date == 'string') {
      return date;
    }

    if (!fmt) fmt = "yyyy-MM-dd hh:mm:ss";

    if (!date || date == null) return null;
    var o = {
      'M+': date.getMonth() + 1, // 月份
      'd+': date.getDate(), // 日
      'h+': date.getHours(), // 小时
      'm+': date.getMinutes(), // 分
      's+': date.getSeconds(), // 秒
      'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
      'S': date.getMilliseconds() // 毫秒
    }
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
    for (var k in o) {
      if (new RegExp('(' + k + ')').test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
    }
    return fmt
  }
</script>

</body>
<style>
  #message-head{
    font-style: oblique;
    color: chocolate;
    /*border: 1px red solid;*/
    padding-left: 45%;
    padding-top: 5%;
  }
  #message{
    border: 1px green solid;
    height: 200px;
  }
  #user_status{
    height: 100px;
    margin-top: 2%;
    border: 1px black solid;
  }
  #message-body{
      /*内容溢出后 滚动条*/
      overflow: scroll;
  }
</style>
</html>
